<template>
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="80%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item label="日期" prop="planActualDate">
            <el-date-picker
              v-model="formData.planActualDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <!--<el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="formData.startTime"
              placeholder="请选择开始时间"
              value-format="HH:mm:ss"
              @change="changePlanBeginTime"
            /
          </el-form-item>>-->
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              :disabled-date="disabledDate"
              placeholder="请选择开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="">
            <el-button plain :disabled="totalMultipleSelection == null" type="warning" @click="timeSort">排序</el-button>
          </el-form-item>
        </el-col>
        <!--<el-col :span="6">
          <el-form-item label="班组" prop="crewId">
            <el-select
              v-model="formData.crewId"
              placeholder="请选择班组"
              @change="changeCrew"
              clearable
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="item.crewName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            ref="dataTableRef"
            max-height="710"
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
            :cell-style="cellStyle"
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              label="计划编号"
              prop="processingOrderNumber"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品图号"
              prop="figureNumber"
              min-width="170"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品名称"
              prop="materialName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="生产日期"
              prop="planActualDate"
              min-width="100"
              show-overflow-tooltip
              align="center"
              :formatter="formatDate"
            />
            <el-table-column
              label="抛丸类型"
              prop="processesClassification"
              min-width="100"
              align="center"
            >
              <template #default="scope">
                <span v-if="scope.row.processesClassification === 7">粗抛</span>
                <span v-if="scope.row.processesClassification === 15"
                  >精抛</span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="生产批次号"
              prop="plannedBatch"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="上工序完成时间"
              prop="lastProcessFinshTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="冷却后时间"
              prop="afterCoolingTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <!--<el-table-column label="计划人员" props="planUsers" min-width="180">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planUserIds'"
                  :rules="rules.sonplanUserIds"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-select
                    v-model="row.memberIds"
                    placeholder="请选择计划人员"
                    clearable
                    style="width: 100%"
                    @change="changePlanUser(row)"
                    filterable
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="1"
                  >
                    <el-option
                      v-for="item in memberList"
                      :key="item.id"
                      :label="`${item.memberName}`"
                      :value="item.memberId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>-->
            <el-table-column
              label="理论时长/分"
              prop="theoreticalTime"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="{ row }">
                {{ Math.ceil(row.theoreticalTime / 60) }}
              </template>
            </el-table-column>
            <el-table-column
              label="计划开始时间"
              prop="planBeginTime"
              min-width="210"
              align="center"
            >
              <!--<template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planBeginTime'"
                  :rules="rules.sonplanBeginTime"
                  label-width="0"
                >
                  <el-date-picker
                    v-model="row.planBeginTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    @change="queryTimeEndOne(row)"
                  />
                </el-form-item>
              </template>-->
            </el-table-column>
            <el-table-column
              label="计划结束时间"
              prop="planEndTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="待料时间/分"
              prop="awaitTime"
              min-width="120"
              show-overflow-tooltip
              align="center"
            />
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          v-if="formData.details.length > 0"
          @click="handleSubmit"
          >提 交</el-button
        >
        <el-button
          type="primary"
          :loading="loading"
          v-if="formData.details.length > 0"
          @click="save"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import {TableResultObject} from "@/views/mes/mesplanmonth/utilejs/interface";
import {ElTable} from "element-plus";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "TIMEADJUST",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
  ],
  sonplanBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
  ],
  startTime: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  details: [],
  crewId: "",
  crewName: "",
  startTime: "",
  planActualDate: getCurrentDate(),
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.crewId = "";
  formData.crewName = "";
  // memberList.value = [];
}

const loading = ref(false);
//提交
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派提交";
      await request({
        url: "/mes/mesplanworkingform/saveBlasting",
        method: "post",
        data: {
          listWorkingForm: formData.details,
          planDate: formData.planActualDate,
        },
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
//保存
function save() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派保存";
      await request({
        url: "/mes/mesplanworkingform/userAssign",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
// const crewList = ref([]);
// async function getCrews() {
//   await request({
//     url: "mes/mescrew/getCrew",
//     method: "post",
//     data: {
//       plantId: formData.plantId,
//       enabled: 1,
//     },
//   }).then((res) => {
//     crewList.value = res.data;
//   });
// }
// function changeCrew(val) {
//   formData.crewId = val;
//   formData.crewName = "";
//   memberList.value = [];
//   formData.details.forEach((item) => {
//     item.planUserIds = "";
//     item.planUsers = "";
//     item.memberIds = [];
//   });
//   if (val) {
//     let crew = crewList.value.find((item) => item.id == val);
//     formData.crewName = crew.crewName;
//     getCrewMembers();
//   }
// }
//人员
// const memberList = ref([]);
// async function getCrewMembers() {
//   await request({
//     url: "mes/mescrew/getCrewMembers",
//     method: "post",
//     data: {
//       id: formData.crewId,
//     },
//   }).then((res) => {
//     memberList.value = res.data;
//   });
// }
// //人员
// const changePlanUser = (row: any) => {
//   row.planUserIds = row.memberIds.join(",");
//   let materialNameList = [];
//   row.memberIds.forEach((item: any) => {
//     memberList.value.forEach((i) => {
//       if (item === i.memberId) {
//         materialNameList.push(i.memberName);
//       }
//     });
//   });
//   row.planUsers = materialNameList.join(",");
//   // changePlanBeginTime(row);
//   queryTimeEndOne(row)
// };
// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
async function getPlanWorkingForm() {
  if (!formData.planActualDate) {
    ElMessage.error("请选择日期");
    return;
  }
  request({
    url: `/mes/mesplanworkingform/queryByList`,
    method: "post",
    data: {
      planActualDate: formData.planActualDate,
      processesClassifications: props.data.processesClassifications,
      isASC: 1,
    },
  })
    .then((res) => {
      formData.details = res.data;
      for (let i = 0; i < formData.details.length; i++) {
        const row = formData.details[i];
        //冷却后时间 = 上工序完成时间+2小时
        // let newVar = new Date(row.lastProcessFinshTime);
        // row.afterCoolingTime = calculateDuration(newVar, 2 * 60 * 60);
        const index = i;
        if (index != 0 && formData.details[index - 1]?.planEndTime) {
          let t1 = new Date(row.planBeginTime).getTime();
          let t2 = new Date(formData.details[index - 1].planEndTime).getTime();
          row.isChangeColor = Math.sign(t1 - new Date(t2 + 300000)) > 0;
          // 待料时间保留秒数
          if (row.isChangeColor) {
            row.awaitTime = Math.floor((t1 - t2) / 60000);
          }
          console.log("row.isChangeColor", row.isChangeColor);
        }
      }
      if (formData.startTime) {
        changePlanBeginTime();
      }
    })
    .catch((res) => {
      console.log(res);
    });
  formRef.value.clearValidate();
}
function changePlanBeginTime() {
  if (!formData.startTime || !formData.details.length) {
    return;
  }
  const t1 = new Date(formData.details[0].afterCoolingTime).getTime();
  const t2 = new Date(
    // formData.planActualDate + " " + formData.startTime
    formData.startTime
  ).getTime();
  if (Math.sign(t1 - t2) > 0) {
    ElMessage.warning("计划开始时间不能小于上工序冷却后时间！");
    return;
  }
  //formData.details[0].planBeginTime = formData.details[0].planBeginTime.split(" ")[0] + " " + formData.startTime;
  request({
    url: `/mes/mesplanworkingform/queryBlastingTimeEnd`,
    method: "post",
    data: {
      listWorkingForm: formData.details,
      // planDate: formData.planActualDate + " " + formData.startTime,
      planDate: formData.startTime,
    },
  })
    .then((res) => {
      formData.details = res.data;
      for (let i = 0; i < formData.details.length; i++) {
        const row = formData.details[i];
        const index = i;
        //冷却后时间 = 上工序完成时间+3小时
        // let newVar = new Date(row.lastProcessFinshTime);
        // row.afterCoolingTime = calculateDuration(newVar, 2 * 60 * 60);
        if (index != 0 && formData.details[index - 1]?.planEndTime) {
          let t1 = new Date(row.planBeginTime).getTime();
          let t2 = new Date(formData.details[index - 1].planEndTime).getTime();
          row.isChangeColor = Math.sign(t1 - new Date(t2 + 300000)) > 0;
          if (row.isChangeColor) {
            row.awaitTime = Math.floor((t1 - t2) / 60000);
          }
        }
      }
    })
    .catch((res) => {
      console.log(res);
    });
  // 上一计划结束时间 等于 下一计划开始时间
  // for (let i = 0; i < formData.details.length; i++) {
  //   if (i == 0) {
  //     formData.details[i].planBeginTime =
  //       formData.details[i].planBeginTime.split(" ")[0] +
  //       " " +
  //       formData.startTime;
  //     formData.details[i].planEndTime = calculateDuration(
  //       formData.details[i].planBeginTime,
  //       formData.details[i].theoreticalTime
  //     );
  //   } else {
  //     if (formData.details[i].planBeginTime) {
  //       formData.details[i].planBeginTime = formData.details[i - 1].planEndTime
  //         ? formData.details[i - 1].planEndTime
  //         : formData.details[i - 1].planEndTimeNew;
  //       formData.details[i].planEndTime = calculateDuration(
  //         formData.details[i].planBeginTime,
  //         formData.details[i].theoreticalTime
  //       );
  //     } else {
  //       formData.details[i].planBeginTimeNew = formData.details[i - 1]
  //         .planEndTime
  //         ? formData.details[i - 1].planEndTime
  //         : formData.details[i - 1].planEndTimeNew;
  //       formData.details[i].planEndTimeNew =
  //         formData.details[i].planBeginTimeNew;
  //     }
  //   }
  // }
}
function calculateDuration(beginTime, time) {
  const start = new Date(beginTime);
  // let number = Math.round(time / 60) * 60 * 1000;
  let number = time * 1000;
  const extendedDate = new Date(start.valueOf() + number);
  const year = extendedDate.getFullYear();
  const month = String(extendedDate.getMonth() + 1).padStart(2, "0");
  const day = String(extendedDate.getDate()).padStart(2, "0");
  const hours = String(extendedDate.getHours()).padStart(2, "0");
  const minutes = String(extendedDate.getMinutes()).padStart(2, "0");
  const seconds = String(extendedDate.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 格式化日期为年月日时分秒
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const makeRange = (start: number, end: number) => {
  const result: number[] = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const disabledHours = () => {
  if (formData.details[0]) {
    return makeRange(
      0,
      formData.details[0]?.lastProcessFinshTime.slice(11, 13) - 1
    );
  }
};
const disabledMinutes = () => {
  if (
    formData.details[0] &&
    formData.startTime.slice(0, 2) ===
      formData.details[0]?.lastProcessFinshTime.slice(11, 13)
  ) {
    return makeRange(
      0,
      formData.details[0]?.lastProcessFinshTime.slice(14, 16) - 1
    );
  }
};
const disabledSeconds = () => {
  if (
    formData.details[0] &&
    formData.startTime.slice(0, 2) ===
      formData.details[0]?.lastProcessFinshTime.slice(11, 13) &&
    formData.startTime.slice(3, 5) ===
      formData.details[0]?.lastProcessFinshTime.slice(14, 16)
  ) {
    return makeRange(
      0,
      formData.details[0]?.lastProcessFinshTime.slice(17, 19) - 1
    );
  }
};
const cellStyle = (data) => {
  if (data.row.isChangeColor) {
    return {
      color: "#000",
      background: "#FBE2E2",
    };
  }
};

const disabledDate = (time) => {
  let date = new Date(formData.planActualDate);
  date.setDate(date.getDate() - 1);
  return time < date.getTime();
};
const dataTableRef = ref<InstanceType<typeof ElTable>>();
const totalMultipleSelection: any = ref(null);
function handleSelectionChange(selection) {
  if (selection.length > 1) {
    const lastSelect = selection[selection.length - 1];
    dataTableRef.value!.clearSelection();
    dataTableRef.value!.toggleRowSelection(lastSelect, true);
  } else {
    totalMultipleSelection.value = selection[0];
  }
}
function timeSort() {
  if (totalMultipleSelection.value == null) {
    ElMessage.warning("请选择要排序的行！");
    return;
  }
  if (!formData.startTime || !formData.details.length) {
    return;
  }
  const t1 = new Date(formData.details[0].afterCoolingTime).getTime();
  const t2 = new Date(
    // formData.planActualDate + " " + formData.startTime
    formData.startTime
  ).getTime();
  if (Math.sign(t1 - t2) > 0) {
    ElMessage.warning("计划开始时间不能小于上工序冷却后时间！");
    return;
  }
  request({
    url: `/mes/mesplanworkingform/queryBlastingTimeEnd`,
    method: "post",
    data: {
      listWorkingForm: formData.details,
      // planDate: formData.planActualDate + " " + formData.startTime,
      planDate: formData.startTime,
      workSequence: formData.details.findIndex((item) => item.id == totalMultipleSelection.value.id) + 1,
    },
  })
    .then((res) => {
      formData.details = res.data;
      for (let i = 0; i < formData.details.length; i++) {
        const row = formData.details[i];
        const index = i;
        //冷却后时间 = 上工序完成时间+3小时
        // let newVar = new Date(row.lastProcessFinshTime);
        // row.afterCoolingTime = calculateDuration(newVar, 2 * 60 * 60);
        if (index != 0 && formData.details[index - 1]?.planEndTime) {
          let t1 = new Date(row.planBeginTime).getTime();
          let t2 = new Date(formData.details[index - 1].planEndTime).getTime();
          row.isChangeColor = Math.sign(t1 - new Date(t2 + 300000)) > 0;
          if (row.isChangeColor) {
            row.awaitTime = Math.floor((t1 - t2) / 60000);
          }
        }
      }
    })
    .catch((res) => {
      console.log(res);
    });
}
</script>
